package com.api.interceptor;

import com.api.annotation.ApiAnnotation;
import com.api.model.TUser;
import com.api.service.UserService;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * Created by rio on 2017/1/17.
 */
public class ApiInterceptor extends HandlerInterceptorAdapter {
    private UserService userService;

    public static TUser getUserByRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        if (request == null) {
            return null;
        }

        Object o = request.getAttribute("user");
        if (o == null || !(o instanceof TUser)) {
            return null;
        }
        return (TUser) o;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            Method method = ((HandlerMethod) handler).getMethod();
            ApiAnnotation annotation = method.getAnnotation(ApiAnnotation.class);
            if (annotation != null) {
                String token = request.getParameter("token");
                if (!StringUtils.isEmpty(token)) {
                    request.getRequestDispatcher("" + "9001").forward(request, response);
                    return false;
                }
                TUser user = userService.findUserByToken(token);
                request.setAttribute("user", user);
                return true;
            }
        }
        return true;

    }
}
